<template>
  <el-card >
     <!-- 面板屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="marginBottom:15px">
        <el-breadcrumb-item :to="{ path: '/' }"
          ><i class="el-icon-s-home"></i> 首页</el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><i class="el-icon-share"></i> 个人中心</el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><i class="el-icon-share"></i> 重置密码</el-breadcrumb-item
        >
      </el-breadcrumb>
    <el-form :model="pwdForm"  ref="pwdRef" label-width="100px" style="width: 500px" :rules="rulesPwd">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input type="password" v-model="pwdForm.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input type="password" v-model="pwdForm.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input type="password" v-model="pwdForm.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="changePwd">修改密码</el-button>
        <el-button @click="$refs.pwdRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { reqUpdatePwd } from '@/api/user'
export default {
  name: 'UserPassword',
  data () {
    const checkpwdRepeat = (rules, value, cb) => {
      if (value !== this.pwdForm.new_pwd) {
        cb(new Error('与新密码输入不一致'))
      } else {
        cb()
      }
    }
    return {
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rulesPwd: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: ['blur', 'change'] },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符串', trigger: ['blur', 'change'] }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: ['blur', 'change'] },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符串', trigger: ['blur', 'change'] }
        ],
        re_pwd: [
          { required: true, message: '请再次输入新密码', trigger: ['blur', 'change'] },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符串', trigger: ['blur', 'change'] },
          { validator: checkpwdRepeat, trigger: ['blur', 'change'] }
        ]
      }

    }
  },
  methods: {
    changePwd () {
      this.$refs.pwdRef.validate(async boo => {
        if (boo) {
          const { data } = await reqUpdatePwd(this.pwdForm)
          console.log(data)
          if (data.code !== 0) return this.$message.error(data.message)
          this.$message.success(data.message)
          this.$router.push('/login')
          localStorage.removeItem('tokenKey')
        }
      })
    }
  }
}
</script>
